#include "StdAfx.h"
#include <opencv\highgui.h>
#include "Frame.hxx"
#include "VIBE.hxx"
#include "FrameArray.hxx"
#include "ForegroundDetectionStep.hxx"
#include "TrackerModel.hxx"
#include "ChannelModel.hxx"
#include "ProcessStream.hxx"
#include "PipeLine.hxx"


ForegroundDetectionStep::ForegroundDetectionStep(ProcessStream* stream):ProcessStep( stream )
{
	_grayImage = 0;
	_segImage = 0;

	_vibe = 0;

	_imageHeader = 0;
}


ForegroundDetectionStep::~ForegroundDetectionStep(void)
{
}

void ForegroundDetectionStep::execute()
{
	FrameArray* frameArray = _stream->getFrameArray();

	Frame* frame = 0;

	bool noAction = true;
	frameArray->lock();

	for( int i = 0; i < frameArray->getPageCount(); i ++ )
	{
		if( frameArray->getFlag( i ) )
		{
			frame = (Frame*)frameArray->getFrameByIndex( i );

			if( frame && frame->ProcessStepFlag == STEP_FOREGROUND_DETECTION )
			{
	
				noAction = false;

				break;
			}
		}
	}
	frameArray->unlock();

	if( noAction ) 
		Sleep( 30 );
	else
	{
		_imageHeader->imageData = frame->FrameImage;

		cvConvertImage( _imageHeader , _inputImage , CV_BGR2GRAY );
		cvResize( _inputImage, _grayImage );

		if( !_vibe )
		{
			_vibe = new VIBE;
			
			_vibe->setFrameWidth( RESIZED_FRAME_WIDTH );
			_vibe->setFrameHeight( RESIZED_FRAME_HEIGHT );
			_vibe->setFrameWidthStrip( _grayImage->widthStep );
			_vibe->setSegmentMap( (unsigned char*)(_segImage->imageData) );
			
			_vibe->setCurrentFrame( (unsigned char*)_grayImage->imageData );
			_vibe->initialize();
		}
		else
		{
			_vibe->setCurrentFrame( (unsigned char*)_grayImage->imageData );
			_vibe->update();
		}

		cvSplit( _imageHeader, _splitImages[ 0 ],_splitImages[ 1 ],_splitImages[ 2 ],0 );

		cvResize( _segImage, _inputImage );

		cvMerge( _splitImages[ 0 ],_splitImages[ 1 ], _inputImage ,0, _maskImage );

		ChannelModel* model = getProcessStream()->getPipeLine()->getTrackerModel()->getSubModel( getProcessStream()->getStreamId() );
		if( model ) model->updateImageData( _maskImage->imageData );

		frame->ProcessStepFlag = STEP_SYNCRONIZE;

		printf("SFIndex:[%d-%05d]\n",getProcessStream()->getStreamId(),frame->FrameIndex );
	}
}

void ForegroundDetectionStep::initialize()
{
	_imageHeader = cvCreateImageHeader( cvSize( RAW_FRAME_WIDTH, RAW_FRAME_HEIGHT ), IPL_DEPTH_8U, 3 );

	_maskImage  = cvCreateImage( cvSize( RAW_FRAME_WIDTH, RAW_FRAME_HEIGHT ), IPL_DEPTH_8U, 3 );
	for( int i = 0; i < 3; i ++ )
		_splitImages[ i ] = cvCreateImage( cvSize( RAW_FRAME_WIDTH, RAW_FRAME_HEIGHT ), IPL_DEPTH_8U, 1 );

	_inputImage = cvCreateImage( cvSize( RAW_FRAME_WIDTH, RAW_FRAME_HEIGHT ), IPL_DEPTH_8U, 1 );

	_grayImage = cvCreateImage( cvSize( RESIZED_FRAME_WIDTH, RESIZED_FRAME_HEIGHT ), IPL_DEPTH_8U, 1 );
	_segImage = cvCreateImage( cvSize( RESIZED_FRAME_WIDTH, RESIZED_FRAME_HEIGHT ), IPL_DEPTH_8U, 1 );

	cvZero( _segImage );
}
